package com.binvshe.binvshe.account.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.account.Account;
import com.binvshe.binvshe.account.AccountManager;
import com.binvshe.binvshe.account.ParamKey;
import com.binvshe.binvshe.account.forgetpwd.ForgetPwdActivity;
import com.binvshe.binvshe.account.regist.RegistActivity;
import com.binvshe.binvshe.account.utils.FragmentUtils;
import com.binvshe.binvshe.account.utils.MD5Util;
import com.binvshe.binvshe.account.utils.RegularUtils;
import com.binvshe.binvshe.app.MainActivity;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.TokenInfo;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.pachong.android.baseuicomponent.activity.BaseActivity;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.frameworkbase.customviews.IconTextArrowEditText;
import com.pachong.android.frameworkbase.customviews.edittext.PasswordEditText;
import com.pachong.android.frameworkbase.dialog.ProgressFragment;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.Bind;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class LoginActivity extends BaseActivity {

    @Bind(R.id.itetPhone)
    IconTextArrowEditText itetPhone;
    @Bind(R.id.itetPassword)
    PasswordEditText mPwetPassword;
    @Bind(R.id.btnLogin)
    Button mBtnLogin;
    @Bind(R.id.tvForget)
    TextView mTvForget;

    public static void start(Activity activity) {
        Intent starter = new Intent(activity, LoginActivity.class);
        activity.startActivity(starter);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initToolBar();
    }

    private void initToolBar() {
        enableBackButton();
        getCustomToolbar().setTitle(R.string.login);
        getCustomToolbar().addRightButton(R.string.register, new RegistBtnListener());
    }

    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.act_login, null);
    }

    private String getPhone() {
        return itetPhone.getEditText().trim();
    }

    private String getPassWord() {
        return mPwetPassword.getPassword().toString();
    }

    @OnClick({R.id.btnLogin, R.id.tvForget})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
                login();
                break;
            case R.id.tvForget:
                ForgetPwdActivity.start(this);
                break;
        }
    }

    private void login() {
        if (TextUtils.isEmpty(getPhone())) {
            FragmentUtils.showWarnDialog("手机号不能为空", getSupportFragmentManager());
            return;
        } else if (TextUtils.isEmpty(getPassWord())) {
            FragmentUtils.showWarnDialog("密码不能为空", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isMobileSimple(getPhone())) {
            FragmentUtils.showWarnDialog("输入的手机号有误", getSupportFragmentManager());
            return;
        } else if (!RegularUtils.isPassword(getPassWord())) {
            FragmentUtils.showWarnDialog("密码最多为6-20个字符", getSupportFragmentManager());
            return;
        }
        String enCodePwd = MD5Util.getMd5(getPassWord());//Md5加密
        setLoginRequest(getPhone(), enCodePwd);
    }

    private ProgressFragment progressFragment = new ProgressFragment();
    private void setLoginRequest(String phone, String password) {

        MyHttpRequest request = new MyHttpRequest(getBaseContext());
        JSONObject jobj = new JSONObject();
        try {
            jobj.put(ParamKey.LOGIN_NAME, phone);
            jobj.put(ParamKey.PASSWORD, password);

            if (!progressFragment.isVisible()) {
                progressFragment.show(getSupportFragmentManager());
            }
            request.post(UrlCenter.LOGIN, jobj, new DataRequestListener<TokenInfo>(TokenInfo.class) {
                @Override
                public void onSuccess(TokenInfo tokenInfo) {
                    Log.e("zf", "login onSuccess  bean == " + tokenInfo);
                    AccountManager.updateTokenInfo(tokenInfo);
                    setAccount(tokenInfo.getUser_id());
                    JPushInterface.resumePush(LoginActivity.this);
                    if (progressFragment.isVisible()) {
                        progressFragment.dismiss();
                    }
                }

                @Override
                public void onStart(Context context, String url) {
                    enableProgress(false);
                    super.onStart(context, url);
                }

                @Override
                public void onFailure(Throwable t, int errorNo, String strMsg) {
                    if (progressFragment.isVisible()) {
                        progressFragment.dismiss();
                    }
                    EasyToast.showToast(getBaseContext(), strMsg);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

   /* *//**
     * 登录环信
     *//*
    private void loginHuanxin() {
        Account acct = AccountManager.getCurrentAccount();
        Log.e("vivi", "  acct getPhone  " + acct.getPhone() + "  pwd " + acct.getPassWord());
        Log.e("vivi", "  acct getUserId  " + acct.getUserId());
        EMClient.getInstance().login(acct.getPhone(), acct.getPassWord(), new EMCallBack() {//回调
            @Override
            public void onSuccess() {
                EMClient.getInstance().groupManager().loadAllGroups();
                EMClient.getInstance().chatManager().loadAllConversations();
                Account acct = AccountManager.getCurrentAccount();
                UserIconMap map = new UserIconMap();
                map.setAvatar(acct.getPortrait());
                map.setUserName(acct.getPhone());
                map.setNickName(acct.getNickName());
                UserIconHelper.setUserIcon(LoginAcivity.this, map);
                Log.d("main", "登录聊天服务器成功！");
            }

            @Override
            public void onProgress(int progress, String status) {

            }

            @Override
            public void onError(int code, String message) {
                Log.d("main", "登录聊天服务器失败！code = " + code);
                Log.d("main", "登录聊天服务器失败！message = " + message);
            }
        });
    }*/


    private void setAccount(String userId) {
        IHttpRequest request = new MyHttpRequest(getBaseContext());
        String requestUrl = String.format(UrlCenter.USER, new Object[]{userId});
        request.get(requestUrl, null, new DataRequestListener<Account>(Account.class) {
            @Override
            public void onSuccess(Account account) {
                Log.e("zf", "Account : " + account);
                account.setPassWord(MD5Util.getMd5("" + mPwetPassword.getPassword()));
                AccountManager.setCurrentAccount(account);
                MainActivity.loginHuanxin(LoginActivity.this);
                EasyToast.showToast(getBaseContext(), "登录成功");
                finish();
            }

            @Override
            public void onStart(Context context, String url) {
                enableProgress(false);
                super.onStart(context, url);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Log.e("zf", "strMsg :" + strMsg);
            }
        });
    }

    private class RegistBtnListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            RegistActivity.start(LoginActivity.this);
        }
    }
}
